import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutterapp/chapter/eleven/user.dart';

/// @date 2020/08/26  15:07
/// @author 程志强
/// @des json to model

class JsonModelRoute extends StatefulWidget {
  @override
  _JsonModelRouteState createState() => _JsonModelRouteState();
}

class _JsonModelRouteState extends State<JsonModelRoute> {
  User _user;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("json model"),
      ),
      body: Column(
        children: <Widget>[
          _user == null
              ? Text("--")
              : Text("json to model:${_user.name}--->${_user.email}"),
          RaisedButton(
            child: Text("json to dart"),
            onPressed: jsonToModel,
          )
        ],
      ),
    );
  }

  // json to model
  jsonToModel() {
    String jsonStr = '{"name":"Jack","email":"john@example.com"}';
    Map<String, dynamic> data = json.decode(jsonStr);
    setState(() {
      _user = User.formJson(data);
    });
  }
}
